package com.oocl.scan.db;

import com.arangodb.ArangoDB;
import com.arangodb.ArangoDatabase;
import com.oocl.scan.utils.PropertiesUtil;

public class ArangoDBConnection {

  private static final String ARANGO_URL = "arango_db_url";
  private static final String ARANGO_PORT = "arango_db_port";
  private static final String ARANGO_USERNAME = "arango_db_username";
  private static final String ARANGO_PASSWORD = "arango_db_password";
  private static final String ARANGO_DB_NAME = "arango_db_name";

  private static final String URL;
  private static final int PORT;
  private static final String USERNAME;
  private static final String PASSWORD;
  private static final String DB_NAME;

  private static volatile ArangoDatabase database;
  private static volatile ArangoDB arangoDB;

  static {
    URL = PropertiesUtil.getPropertyByName(ARANGO_URL);
    PORT = Integer.parseInt(PropertiesUtil.getPropertyByName(ARANGO_PORT));
    USERNAME = PropertiesUtil.getPropertyByName(ARANGO_USERNAME);
    PASSWORD = PropertiesUtil.getPropertyByName(ARANGO_PASSWORD);
    DB_NAME = PropertiesUtil.getPropertyByName(ARANGO_DB_NAME);
  }

  public static ArangoDatabase getInstance() {
    if (database == null) {
      synchronized (ArangoDBConnection.class) {
        if (database == null) {
          arangoDB = new ArangoDB.Builder().host(URL, PORT).user(USERNAME).password(PASSWORD).build();
          database = arangoDB.db(DB_NAME);
        }
      }
    }
    return database;
  }

  public static void shutdown(){
    if(arangoDB != null && database != null){
      arangoDB.shutdown();
      arangoDB = null;
      database = null;
    }
  }
}
